/*
 * -\-\-
 * Mobius
 * --
 * Copyright (c) 2017-2020 Spotify AB
 * --
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * -/-/-
 */

package com.spotify.mobius.ohos.runners;


import com.spotify.mobius.runners.WorkRunner;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * A work runner that uses a Looper to run work.
 */
public class LooperWorkRunner implements WorkRunner {
    private final EventHandler handler;
    private volatile boolean disposed;

    LooperWorkRunner() {
        this.handler = new EventHandler(EventRunner.getMainEventRunner());
    }

    /**
     * Will cancel all Runnables posted to this looper.
     */
    @Override
    public void dispose() {
        handler.removeAllEvent();
        disposed = true;
    }

    /**
     * Will post the provided runnable to the looper for processing.
     *
     * @param runnable the runnable you would like to execute
     */
    @Override
    public void post(Runnable runnable) {
        if (disposed) {
            return;
        }
        handler.postSyncTask(runnable);
    }

    /**
     * Creates a {@link WorkRunner} backed by the provided Looper}
     *
     * @return a {@link WorkRunner} that uses the provided Looper for processing work
     */
    public static LooperWorkRunner using() {
        return new LooperWorkRunner();
    }
}
